import { defineStore } from 'pinia'
import { reqLogin, reqUserInfoByOwner, reqLogout } from '@/api/user'
import { useChatStore } from '../chat'


export const useUserStore = defineStore('user', {
  state: () => {
  return {
    token: localStorage.getItem('token'),
    uid: '',
    email: '',
    avatar: '',
    nickname: '',
  }
},
  actions: {
  async login(data) {
    const res = await reqLogin(data)
    if (res.code === 200) {
      this.token = res.data
      localStorage.setItem('token', res.data)
      return this.token
    } else {
      return Promise.reject(new Error(res.message))
    }
  },
  async userInfo() {
    const res = await reqUserInfoByOwner()
    if (res.code === 200) {
      const { email, avatar , nickname , uid} = res.data
      this.uid = uid
      this.email = email
      this.avatar = avatar
      this.nickname = nickname
      window.ipcRenderer.send('init-user' , res.data)
      return res.data
    } else {
      return Promise.reject(new Error(res.message))
    }
  },
  async logout() {

    const chatStore = useChatStore()
    const res = await reqLogout()
    if (res.code === 200) {
      this.email = ''
      this.avatar = ''
      this.uid = ''
      this.nickname = ''
      this.token = ''
      localStorage.removeItem('token')
      chatStore.clear()
      return true
    } else {
      return Promise.reject(new Error(res.message))
    }
  },
},
getters: {},
})
